package com.hitqz.robot.daemon.quartz.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hitqz.robot.api.business.dto.GoodsBufferDetailDto;
import com.hitqz.robot.api.business.dto.GoodsBufferDto;
import com.hitqz.robot.api.business.dto.SubscriptTopicDto;
import com.hitqz.robot.api.business.entity.GoodsBuffersEntity;
import com.hitqz.robot.api.business.entity.GoodsGroupEntity;
import com.hitqz.robot.api.business.entity.JobCachesEntity;
import com.hitqz.robot.api.business.entity.RobotJobEntity;
import com.hitqz.robot.api.dispatch.protocol.dto.FormConfigModalDto;
import com.hitqz.robot.api.dispatch.protocol.dto.FormFieldConfigModalDto;
import com.hitqz.robot.biz.service.GoodsBuffersService;
import com.hitqz.robot.biz.service.GoodsGroupService;
import com.hitqz.robot.biz.service.JobCachesService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.daemon.quartz.model.km.KmAgvCallResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author xupkun
 * @date 2025/2/20
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("km")
@Tag(name = "AGV呼叫系统--昆明北车辆段")
@Slf4j
public class KmAgvController {

    private final RestTemplate restTemplate;

    private final JobCachesService jobCachesService;

    private final GoodsBuffersService goodsBuffersService;

    private final GoodsGroupService goodsGroupService;
    //private static final Map<String, RateLimiter> topicRateLimiterMap = new ConcurrentHashMap<>(8);

    /***
     * 双轮对
     *  01N01-> 01N03 轮轴分离 (完成）
     *  45NX -> 45N01 60T 支出 （完成）
     *。45NX-> 45N02 70T支出  （完成）
     *。20S04-> 20S05 返厂AGV （完成， 但AGV还不能走）
     * 22N05 -> 40N01
     *
     * @param src
     * @param des
     * @param data
     * @return
     */

    @PostMapping(value = "/agv/call")
    @Operation(summary = "昆明北车辆段-AGV呼叫")
    public KmAgvCallResult callAgv(@RequestParam String src,
                                   @RequestParam String des,
                                   @RequestParam(required = false) String outType,
                                   @RequestParam(required = false) String pjid,
                                   @RequestParam(required = false) String pjid1,
                                   @RequestParam(required = false) String pjid2,
                                   @RequestParam(required = false) String zx,
                                   HttpServletRequest request) {
        KmAgvCallResult result = new KmAgvCallResult();
        result.setCode(200);
        if (src.equals("22N05") && des.equals("40S01")) {
            // 复-北 关-南
        } else if (src.equals("22N05") && des.equals("40N01")) {
            // 复-北 关-北
        } else if (src.equals("22S05") && des.equals("40S01")) {
            // 复-南 关-南
        } else if (src.equals("22S05") && des.equals("40N01")) {
            // 复-南 关-北
        }

        String uri = createTaskName(src, des , false);
        if (StrUtil.isNotEmpty(outType)) {
            uri +="&outType=" + outType;
        }
        if (StrUtil.isNotEmpty(pjid)) {
            // 交接位置
            uri +="&pjid=" + pjid + "&putType=2&sbbh_src=" + src;
        }
        if (StrUtil.isNotEmpty(pjid1)) {
            uri +="&pjid1=" + pjid1;
        }
        if (StrUtil.isNotEmpty(pjid2)) {
            uri +="&pjid2=" + pjid2;
        }
        if (StrUtil.isNotEmpty(zx)) {
            uri +="&zx=" + zx;
        }
        try {
            String sendResult = restTemplate.postForObject(uri, "", String.class);
            log.info("分发AGV任务{} 的结果：{}", uri, sendResult);
        } catch (Exception e) {
            log.info("分发数据发生异常{}", e.getMessage());
            result.setCode(500);
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    public String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }


    @PostMapping(value = "/agv/call/dispatch")
    @Operation(summary = "昆明北车辆段-AGV呼叫-根据不同设备进行分发")
    public KmAgvCallResult callAgvDispatch(@RequestParam String src,
                                   @RequestParam String des,
                                   @RequestParam Integer groupId,@RequestParam(required = false) String outType,
                                           @RequestParam(required = false) String pjid,
                                           @RequestParam(required = false) String pjid1,
                                           @RequestParam(required = false) String pjid2,
                                           @RequestParam(required = false) String zx,
                                           @RequestParam(required = false) String putType,
                                           @RequestParam(required = false) String sbbh_src

    ) {
        KmAgvCallResult result = new KmAgvCallResult();
        result.setCode(200);
        result.setAgvSn("");
        result.setMsg("操作成功");
        try {
            String taskName = createTaskName(src, des, true);
            if (StrUtil.isEmpty(des) && src.equals("45NX")) {
                des = findGoodsBuffer(2);
                log.info("临时修预计放在：" + des);
            } else if (src.equals("") &&  (des.equals("5211") || des.equals("5210") || des.equals("5209")
                    || des.equals("5208") || des.equals("5207") || des.equals("5206") || des.equals("5205") || des.equals("5204")
                    || des.equals("5203"))) {
                src = findGoodsBuffer(1);
                log.info("轴承推卸替换预计放在:" + src);
                String middle = des;
                des = src;
                src = middle;
            } else if (src.isEmpty() && des.equals("01N03")) {
                src = findFetchStore(2);
                log.info("临时修预计取轮在：" + src);
            }
            RobotJobEntity robotJob =  new RobotJobEntity();
            robotJob.setCron("0 * * * * ?");
            robotJob.setName(taskName + ":时间-" + DateUtil.format(new Date(), "yyyyMMddHH:mm:ss") );
            robotJob.setGroupId(6);
            String content ="{\"robotSn\":\"sr_002\",\"id\":null,\"formTitle\":\"运输工单上下文参数配置\",\"formName\":\"tickets_params_agv\",\"fields\":[{\"id\":45,\"name\":\"targetPosCode\",\"label\":\"目标点位编码\",\"type\":\"radio\",\"defaultValue\":null,\"currentValue\":\"LM34\",\"required\":true,\"min\":null,\"max\":null,\"pattern\":null,\"options\":[\"{\\\"label\\\":\\\"LM34\\\",\\\"value\\\":\\\"LM34\\\"}\"]},{\"id\":46,\"name\":\"sourcePosCode\",\"label\":\"起始点位编码\",\"type\":\"radio\",\"defaultValue\":null,\"currentValue\":\"LM23\",\"required\":true,\"min\":null,\"max\":null,\"pattern\":null,\"options\":[\"{\\\"label\\\":\\\"LM23\\\",\\\"value\\\":\\\"LM23\\\"}\"]}]}";
            content = content.replaceAll("LM34", des).replaceAll("LM23", src);

            FormConfigModalDto jsonArray = JSONObject.parseObject(content, FormConfigModalDto.class);
            List<FormFieldConfigModalDto> formFieldConfigModalDtos = jsonArray.getFields();
            FormFieldConfigModalDto dto = new FormFieldConfigModalDto();

            dto = new FormFieldConfigModalDto();
            dto.setLabel("srcnum");
            dto.setName("srcnum");
            dto.setCurrentValue("1");
            formFieldConfigModalDtos.add(dto);
            dto = new FormFieldConfigModalDto();
            Map<String, String> pjData = Maps.newHashMap();
            String[] keys = {"outType", "pjid", "pjid1", "pjid2", "zx", "putType", "sbbh_src"};
            String[] values = {outType, pjid, pjid1, pjid2, zx,putType, sbbh_src };
            for (int i = 0; i < keys.length; i++) {
                String key = keys[i];
                String value = values[i];
                if (StrUtil.isNotEmpty(value)) {
                    pjData.put(key, value);
                }
            }
            dto.setLabel("pjData");
            dto.setName("pjData");
            dto.setCurrentValue(JSONObject.toJSONString(pjData));
            formFieldConfigModalDtos.add(dto);
            dto = new FormFieldConfigModalDto();
            dto.setLabel("auto");
            dto.setName("auto");
            dto.setCurrentValue("1");
            formFieldConfigModalDtos.add(dto);

            jsonArray.setFields(formFieldConfigModalDtos);
            robotJob.setContent(JSONObject.toJSONString(jsonArray));
            // 先查询执行的顺序
            JobCachesEntity jobCachesEntity = new JobCachesEntity();
            // 两边都分配固定的分组id---分组id
            jobCachesEntity.setGroupId(groupId);
            jobCachesEntity.setTaskName(taskName);
            jobCachesEntity.setJobType(jobCachesEntity.getTaskName());
            // 执行的顺序
            Long maxSn = jobCachesService.getMaxSn(6);
            jobCachesEntity.setSn((int) (1 + maxSn));
            jobCachesEntity.setTaskContent(robotJob.getContent());
            jobCachesService.save(jobCachesEntity);
            SpringUtil.getApplicationContext().publishEvent(new SubscriptTopicDto("jobCaches"));
            return result;
        } catch (Exception e) {
            log.info("数据异常无法解析:" + e.getMessage());
            result.setCode(400);
            result.setMsg(e.getMessage());
            return result;
        }
    }



    public String createTaskName(String src, String des, boolean returnTaskName) {
        String taskName = "";
        String uri = "http://ip:9999/admin/km/agv/call/dispatch?src=" + src + "&des=" + des + "&groupId=executeGroupId";
        if (src.equals("01N01") && des.equals("01N03")) {
            // 双轮对
            taskName = "轮轴分离-轮轴收入";
            uri = uri.replace("ip", "localhost").replace("executeGroupId", "11");
        }else if (src.equals("45NX") && des.equals("")) {
            // 双轮对
            taskName = "轮轴支出-临修";
            uri = uri.replace("ip", "192.10.11.152").replace("executeGroupId", "6");
        }  else if (src.equals("45NX") && des.equals("45N01")) {
            // 双轮对
            taskName = "轮轴支出-60T";
            uri = uri.replace("ip", "192.10.11.152").replace("executeGroupId", "6");
        } else if (src.equals("45NX") && des.equals("45N02")) {
            // 双轮对
            taskName = "轮轴支出-70T";
            uri = uri.replace("ip", "192.10.11.152").replace("executeGroupId", "6");
        } else if (src.equals("20S04") && des.equals("20S05")) {
            // 返厂AGV
            taskName =  "22S前返厂暂停位置";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "14");
        } else if (src.equals("22S05") && des.equals("22S06")) {
            // 单轮对
            taskName = "人工复探(南)-压装";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "17");
        } else if (src.equals("22S05") && des.equals("22N06")) {
            // 单轮对
            taskName = "人工复探(南)-镟修";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "17");
        }  else if (src.equals("22S05") && (des.equals("566"))) {
            // 单轮对
            taskName = "人工复探(南)-缓存架";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "17");
        } else if (src.equals("22N05") && des.equals("566")) {
            // 单轮对
            taskName = "人工复探(北)-缓存架";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "6");
        } else if (src.equals("566") && des.equals("40N01")) {
            // 单轮对
            taskName = "缓存架-关盖(北)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "10");
        } else if (src.equals("566") && des.equals("40S01")) {
            // 单轮对
            taskName = "缓存架-关盖(南)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "10");
        }  else if (src.equals("22N05") && des.equals("22N06")) {
            // 单轮对
            taskName = "人工复探(北)-镟修";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "6");
        } else if (src.equals("22N05") && des.equals("22S06")) {
            // 单轮对
            taskName = "人工复探(北)-压装";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "6");
        } else if (src.equals("22N08") && des.equals("40S01")) {
            taskName =  "镟修-关盖(南)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "10");
        } else if (src.equals("22N08") && des.equals("40N01")) {
            taskName =  "镟修-关盖(北)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "10");
        } else if (src.equals("34S02") && des.equals("40S01")) {
            taskName =  "压装(南)-关盖(南)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "16");
        } else if (src.equals("34N04") && des.equals("40N01")) {
            taskName =  "压装(北)-关盖(北)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "16");
        } else if (src.equals("34S02") && des.equals("40N01")) {
            taskName =  "压装(南)-关盖(北)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "16");
        } else if (src.equals("34N04") && des.equals("40S01")) {
            taskName =  "压装(北)-关盖(南)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "16");
        }else if (src.equals("22N05") && des.equals("40S01")) {
            taskName =  "人工复探(北)-关盖(南)";
        } else if (src.equals("22N05") && des.equals("40N01")) {
            taskName =  "人工复探(北)-关盖(北)";
        } else if (src.equals("22S05") && des.equals("40S01")) {
            taskName =  "人工复探(南)-关盖(南)";
        } else if (src.equals("22S05") && des.equals("40N01")) {
            taskName =  "人工复探(南)-关盖(北)";
        } else if (src.equals("22N07") && des.equals("30S01")) {
            // 压装间AGV
            taskName =  "镟修-压装-70T";
            uri = uri.replace("ip", "192.10.11.154").replace("executeGroupId", "6");
        } else if (src.equals("22N07") && des.equals("30N01")) {
            // 压装间AGV
            taskName =  "镟修-压装-60T";
            uri = uri.replace("ip", "192.10.11.154").replace("executeGroupId", "6");
        } else if (src.isEmpty() &&
                (des.equals("5232") || des.equals("5233") || des.equals("5234") ) ) {
            // 地牛叉车
            taskName = "压装间托盘替换";
            uri = uri.replace("ip", "192.10.11.154").replace("executeGroupId", "6");
        } else if (des.isEmpty() &&  (src.equals("5211") || src.equals("5210") || src.equals("5209")
             || src.equals("5208") || src.equals("5207") || src.equals("5206") || src.equals("5205") || src.equals("5204")
                 || src.equals("5203"))) {
            // 平衡重叉车
            taskName = "轴承推卸智能替换";
            uri = uri.replace("ip", "192.10.11.155").replace("executeGroupId", "6");
        } else if (des.isEmpty() &&  (src.equals("5202") || src.equals("5201"))) {
            // 平衡重叉车
            taskName = "后挡料箱推卸替换";
            uri = uri.replace("ip", "192.10.11.155").replace("executeGroupId", "6");
        } else if (src.isEmpty() && des.equals("5241,5242")) {
            // 潜伏AGV
            taskName = "关盖换料(北)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "15");
        } else if (src.isEmpty() && des.equals("5243,5244")) {
            // 潜伏AGV
            taskName = "关盖换料(南)";
            uri = uri.replace("ip", "192.10.11.153").replace("executeGroupId", "15");
        } else if (src.isEmpty() && des.equals("01N03")) {
            taskName = "厂修-收入";
            uri = uri.replace("ip", "192.10.11.152").replace("executeGroupId", "11");
        }
        return returnTaskName ? taskName : uri;
    }

    /**
     * 查询存放的位置
     * @param num
     * @return
     */
    private String findGoodsBuffer(Integer num) {
        List<GoodsGroupEntity> goodsGroupEntities = goodsGroupService.list();
        // 查询第一条是否满足条件
        List<GoodsBuffersEntity> goodsBuffersEntities = Lists.newArrayList();
        for (GoodsGroupEntity goodsGroupEntity : goodsGroupEntities) {
            if (goodsGroupEntity.getStatus() == 1) {
                // 先找第一排缓存架
                List<GoodsBuffersEntity> allGoods = goodsBuffersService.list(
                        Wrappers.<GoodsBuffersEntity>lambdaQuery()
                                .eq(GoodsBuffersEntity::getRealStoreName, "km")
                                .eq(GoodsBuffersEntity::getStoreStatus, 1)
                                .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                                .orderByDesc(GoodsBuffersEntity::getSn)
                );
                if (num > allGoods.size()) {
                    log.info("{} 缓存架数量不足：{}, {}", goodsGroupEntity.getName(), num, allGoods.size());
                    continue;
                }
                while (true) {
                    List<GoodsBuffersEntity> findGoods = findContinuousStoreStatusOne(allGoods, 1);
                    if (findGoods.isEmpty()) {
                        log.info("{} 找不到合适的缓存架位置：{}, {}", goodsGroupEntity.getName(), num, allGoods.size());
                        break;
                    }
                    // 查询是不是最后面
                    int endSn = findGoods.get(findGoods.size() - 1).getSn() +1;
                    log.info("下一个的序号是:" + endSn);
                    GoodsBuffersEntity nextGoodsBuffersEntities = goodsBuffersService.getOne(
                            Wrappers.<GoodsBuffersEntity>lambdaQuery().eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                                    .eq(GoodsBuffersEntity::getSn, endSn)
                                    .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                    );
                    if (nextGoodsBuffersEntities != null) {
                        if (nextGoodsBuffersEntities.getStoreStatus() == 0) {
                            log.info("属于中间被人抽走的情况:" + nextGoodsBuffersEntities.getName());
                            for (int i=0;i< num; i++) {
                                allGoods.remove(i);
                            }
                            continue;
                        }
                    }
                    goodsBuffersEntities = findGoods;
                    break;
                }
                if (!goodsBuffersEntities.isEmpty()) {
                    break;
                }
            }
        }
        if (!goodsBuffersEntities.isEmpty()) {
            // 更新
            for (int i = 0; i < num; i++) {
                GoodsBuffersEntity saveGood = goodsBuffersEntities.get(i);
                // 绑定存放
                saveGood.setStoreStatus(2);
                goodsBuffersService.updateById(saveGood);
            }
            return goodsBuffersEntities.get(0).getBindPosName();
        }
        return "";
    }

    /**
     * 查询出序号连续且为空的元素
     * @param allGoods
     * @return
     */
    public static List<GoodsBuffersEntity> findContinuousStoreStatusOne(List<GoodsBuffersEntity> allGoods, int status) {
        List<GoodsBuffersEntity> findGoodsBuffer = Lists.newArrayList();
        if (allGoods == null || allGoods.isEmpty()) {
            return findGoodsBuffer;
        }
        // 按照 sn 排序，确保序号是连续的
        if (status == 1) {
            allGoods.sort(Comparator.comparingInt(GoodsBuffersEntity::getSn));
        }
        for (int i = 0; i < allGoods.size(); i++) {
            GoodsBuffersEntity current = allGoods.get(i);
            if (current.getStoreStatus() == status) {
                GoodsBuffersEntity next = allGoods.get(Math.min(i+1,  allGoods.size()-1));
                if ((next.getStoreStatus() == 1)
                        && ((current.getSn() + 1) == next.getSn())) {
                    findGoodsBuffer.add(current);
                    findGoodsBuffer.add(next);
                    break;
                }
                if ((next.getStoreStatus() == 0)
                        && ((current.getSn() - 1) == next.getSn())) {
                    findGoodsBuffer.add(next);
                    findGoodsBuffer.add(current);
                    break;
                }
            }
        }

        return findGoodsBuffer;
    }


    /**
     * 查询可取走位置
     * @param num
     * @return
     */
    private String findFetchStore(Integer num) {
        List<GoodsGroupEntity> goodsGroupEntities = goodsGroupService.list();
        // 查询第一条是否满足条件
        List<GoodsBuffersEntity> goodsBuffersEntities = Lists.newArrayList();
        for (GoodsGroupEntity goodsGroupEntity : goodsGroupEntities) {
            if (goodsGroupEntity.getStatus() == 1) {
                // 先找第一排缓存架
                List<GoodsBuffersEntity> allGoods = goodsBuffersService.list(
                        Wrappers.<GoodsBuffersEntity>lambdaQuery()
                                .eq(GoodsBuffersEntity::getRealStoreName, "fetch")
                                .eq(GoodsBuffersEntity::getStoreStatus, 0)
                                .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                                .orderByDesc(GoodsBuffersEntity::getSn)
                );
                if (num > allGoods.size()) {
                    //log.info("{} 取缓存架数量不足：{}, {}", goodsGroupEntity.getName(), num, allGoods.size());
                    continue;
                }
                while (true) {
                    List<GoodsBuffersEntity> findGoods = findContinuousStoreStatusOne(allGoods, 0);
                    if (findGoods.isEmpty()) {
                        //log.info("{} 取找不到合适的缓存架位置：{}, {}", goodsGroupEntity.getName(), num, allGoods.size());
                        break;
                    }
                    // 查询是不是最后面
                    int endSn = findGoods.get(findGoods.size() - 1).getSn() +1;
                    log.info("下一个的序号是:" + endSn);
                    GoodsBuffersEntity nextGoodsBuffersEntities = goodsBuffersService.getOne(
                            Wrappers.<GoodsBuffersEntity>lambdaQuery().eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                                    .eq(GoodsBuffersEntity::getSn, endSn)
                                    .eq(GoodsBuffersEntity::getGroupId, goodsGroupEntity.getId())
                    );
                    if (nextGoodsBuffersEntities != null) {
                        if (nextGoodsBuffersEntities.getStoreStatus() == 0) {
                            //log.info("属于中间被人抽走的情况:" + nextGoodsBuffersEntities.getName());
                            for (int i=0;i< num; i++) {
                                allGoods.remove(i);
                            }
                            continue;
                        }
                    }
                    goodsBuffersEntities = findGoods;
                    break;
                }
            }
        }
        if (!goodsBuffersEntities.isEmpty()) {
            // 更新
            for (int i = 0; i < num; i++) {
                GoodsBuffersEntity saveGood = goodsBuffersEntities.get(i);
                // 绑定存放
                saveGood.setStoreStatus(2);
                goodsBuffersService.updateById(saveGood);
            }
            return goodsBuffersEntities.get(0).getBindPosName();
        }
        return "";


    }

    @Operation(summary = "更新缓存架状态")
    @PostMapping(value = "/agv/updateGoodsStore")
    public KmAgvCallResult updateGoodsStore(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status
    ) {
        KmAgvCallResult kmAgvCallResult = new KmAgvCallResult();
        GoodsBuffersEntity goodsBuffersEntity = goodsBuffersService.getOne(
                Wrappers.<GoodsBuffersEntity>lambdaQuery()
                        .eq(GoodsBuffersEntity::getStoreName, name)
        );

        if (goodsBuffersEntity != null) {
            int lastStatus = goodsBuffersEntity.getStoreStatus();
                    log.info("更新缓存架数据:{}--{}", goodsBuffersEntity.getName(), status);
            goodsBuffersService.update(Wrappers.<GoodsBuffersEntity>lambdaUpdate()
                    .eq(GoodsBuffersEntity::getId, goodsBuffersEntity.getId())
                    .set(GoodsBuffersEntity::getStoreStatus, status)
                            .set(GoodsBuffersEntity::getLastStoreStatus, lastStatus)
                    .set(GoodsBuffersEntity::getStoreTime, new Date())
            );
        }
        return kmAgvCallResult;
    }


    //private boolean isSequenceContinuous(List<GoodsBuffersEntity> allGoods) {
    //    if (allGoods == null || allGoods.size() < 2) {
    //        return true; // 如果列表为空或只有一个元素，则认为是连续的
    //    }
    //    // 按照序号排序
    //    allGoods.sort(Comparator.comparingInt(GoodsBuffersEntity::getSn));
    //    for (int i = 1; i < allGoods.size(); i++) {
    //        if (allGoods.get(i).getSn() != allGoods.get(i - 1).getSn() + 1) {
    //            return false; // 如果当前序号不等于前一个序号加1，则不连续
    //        }
    //    }
    //    return true; // 所有序号连续
    //}


    @Operation(summary = "获取缓存架状态-如果缓存架是空的状态进行占用")
    @GetMapping(value = "/agv/getStoreStatus")
    public KmAgvCallResult getStoreStatus(
            @RequestParam(required = false) String name,
            @RequestParam(value = "clientId") String clientId
    ) {
        KmAgvCallResult kmAgvCallResult = new KmAgvCallResult();
        kmAgvCallResult.setCode(2000);
        synchronized (this) {
            GoodsBuffersEntity goodsBuffersEntity = goodsBuffersService.getOne(
                    Wrappers.<GoodsBuffersEntity>lambdaQuery()
                            .eq(GoodsBuffersEntity::getName, name)
            );
            if (goodsBuffersEntity.getStoreStatus() == 1) {
                // 无存放, 先占用
                goodsBuffersEntity.setRealStoreName(clientId);
                goodsBuffersEntity.setStoreStatus(2);
                goodsBuffersService.updateById(goodsBuffersEntity);
                kmAgvCallResult.setData("1");
                return kmAgvCallResult;
            } else {
                kmAgvCallResult.setData(goodsBuffersEntity.getStoreStatus() + "");
                return kmAgvCallResult;
            }
        }
    }

    /**
     * 查询当前缓存架的状态
     * @return
     */
    @Operation(summary = "获取缓存架数据")
    @GetMapping(value = "/agv/goodBufferStatus")
    public R<GoodsBuffersEntity> goodBufferStatus(@RequestParam String name) {
        return R.ok(goodsBuffersService.getOne(
                Wrappers.<GoodsBuffersEntity>lambdaQuery()
                        .eq(GoodsBuffersEntity::getName, name)
        ));
    }


    @Operation(summary = "根据分组取缓存架状态")
    @GetMapping(value = "/agv/goodsStatusByGroup/{groupId}")
    public R<GoodsBufferDto> goodsStatusName(@PathVariable Integer groupId) {
        List<GoodsBuffersEntity> goodsBuffersEntities = goodsBuffersService.list(
                Wrappers.<GoodsBuffersEntity>lambdaQuery()
                        .eq(GoodsBuffersEntity::getGroupId, groupId)
        );
        List<GoodsBufferDetailDto> goodsBufferDtos = new ArrayList<>();
        for (GoodsBuffersEntity goodsBuffersEntity : goodsBuffersEntities) {
            GoodsBufferDetailDto goodsBufferDto = new GoodsBufferDetailDto();
            goodsBufferDto.setName(goodsBuffersEntity.getName());
            goodsBufferDto.setStoreName(goodsBuffersEntity.getStoreName());
            goodsBufferDto.setStoreStatus(goodsBuffersEntity.getStoreStatus());
            goodsBufferDto.setBindPosName(goodsBuffersEntity.getBindPosName());
            goodsBufferDto.setBindPosId(goodsBuffersEntity.getBindPosId());
            goodsBufferDtos.add(goodsBufferDto);
        }
        GoodsBufferDto bufferDto = new GoodsBufferDto();
        bufferDto.setDtoList(goodsBufferDtos);
        bufferDto.setGroupName("测试组");
        return R.ok(bufferDto);
    }





    @Operation(summary = "更新缓存架托盘状态")
    @PostMapping(value = "/agv/updateTrayStatus")
    public KmAgvCallResult updateTrayStatus(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status
    ) {
        KmAgvCallResult kmAgvCallResult = new KmAgvCallResult();
        GoodsBuffersEntity goodsBuffersEntity = goodsBuffersService.getOne(
                Wrappers.<GoodsBuffersEntity>lambdaQuery()
                        .eq(GoodsBuffersEntity::getStoreName, name)
        );
        if (goodsBuffersEntity != null) {
            if (goodsBuffersEntity.getStoreStatus() == 1 && status ==0) {
                // 空托盘入库
                status = 3;
            } else if (goodsBuffersEntity.getStoreStatus() == 3 && status == 1) {
                // 满托盘入库
                status = 4;
            } else if (goodsBuffersEntity.getStoreStatus() == 4 && status == 0) {
                // 满托出库
                status = 1;
            }
            log.info("更新托盘数据:{}--{}", goodsBuffersEntity.getName(), status);
            goodsBuffersService.update(Wrappers.<GoodsBuffersEntity>lambdaUpdate()
                    .eq(GoodsBuffersEntity::getId, goodsBuffersEntity.getId())
                    .set(GoodsBuffersEntity::getStoreStatus, status)
                    .set(GoodsBuffersEntity::getStoreTime, new Date())
            );
        }
        return kmAgvCallResult;
    }

}
